package com.example.review;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.Toast;

/**
 * 动态广播
 */
public class chapterFive2Activity extends AppCompatActivity {

    private IntentFilter intentFilter;
    private NetWorkChangeReceiver networkChangeReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chapter_five2);
        //创建了一个IntentFilter 的实例，并给它添加了一个 值为android.net.conn.CONNECTIVITY_CHANGE 的action
        intentFilter =new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        networkChangeReceiver=new NetWorkChangeReceiver();
        //将接收器和接受的广播进行注册
        registerReceiver(networkChangeReceiver,intentFilter);
    }

    @Override
    //特别注意  动态注册的广播接收器一定都要取消注册才行
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(networkChangeReceiver);
    }




    /**
     * 新建一个类，让它继承自 BroadcastReceiver ，并重写父类的onReceive() 方法
     */
    class NetWorkChangeReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager connectivityManager=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isAvailable()){
                Toast.makeText(context, "当前有网络", Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(context, "网络飞走了", Toast.LENGTH_SHORT).show();
            }
        }
    }









    /**
     * 新建一个类，让它继承自 BroadcastReceiver ，并重写父类的onReceive() 方法
     *//*
    class NetWorkChangeReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "网络发生了变化", Toast.LENGTH_SHORT).show();
        }
    }*/
}